package com.zhongxi.guoyuan.view.user.gift;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.GiftResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.widget.webview.ArticleWebView;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Iterator;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GiftDetailActivity extends BaseActivity {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.giftDetail_top_Name)
    TextView giftDetailTopName;
    @Bind(R.id.giftDetail_top_time)
    TextView giftDetailTopTime;
    @Bind(R.id.giftDetail_top_describe)
    TextView giftDetailTopDescribe;
    @Bind(R.id.giftDetail_center_name)
    TextView giftDetailCenterName;
    @Bind(R.id.giftDetail_center_iamge)
    ImageView giftDetailCenterIamge;
    @Bind(R.id.wv)
    ArticleWebView webView;
    @Bind(R.id.gift_bottom_time)
    TextView getGiftDetailBottomTime;
    @Bind(R.id.giftDetail_bottom_image)
    ImageView giftDetailBottomImage;
    @Bind(R.id.giftDetail_bottom_name)
    TextView giftDetailBottomName;
    @Bind(R.id.giftDetail_bottom_category)
    TextView giftDetailBottomCategory;
    @Bind(R.id.giftDetail_bottom_marketPrice)
    TextView giftDetailBottomMarketPrice;
    @Bind(R.id.giftDetail_bottom_friendPrice)
    TextView giftDetailBottomFriendPrice;
    @Bind(R.id.giftDetail_bottom_saveMoney)
    TextView giftDetailBottomSaveMoney;
    @Bind(R.id.giftDetail_bottom_friendMeidou)
    TextView giftDetailBottomFriendMeidou;
    @Bind(R.id.giftDetail_bottom_friendHongdou)
    TextView giftDetailBottomFriendHongdou;
    @Bind(R.id.giftDetail_bottom_friendOtherGet)
    TextView giftDetailBottomFriendOtherGet;
    @Bind(R.id.tvShare)
    TextView tvShare;
    @Bind(R.id.giftDetail_bottom_sharerGet)
    TextView giftDetailBottomSharerGet;
    @Bind(R.id.giftDetail_bottom_shopName)
    TextView giftDetailBottomShopName;
    @Bind(R.id.giftDetail_bottom_shopPhone)
    TextView giftDetailBottomShopPhone;
    @Bind(R.id.giftDetail_bottom_shopAddress)
    TextView giftDetailBottomShopAddress;
    @Bind(R.id.myScrollView)
    ScrollView scrollView;
    @Bind(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @Bind(R.id.title)
    View title;
    private GiftResult result;
    private String type;
    private PopupWindow popupWindow;
    private View popupWindow_view;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;


    private String aid;
    public static final int resultGift = 1000;
    private GiftResult.GiftActivity activity;
    private GiftResult.RefInfo refInfo;
    private GiftResult.StoreInfo storeInfo;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_gift_detail);
        ButterKnife.bind(this);
        initTitle();
        mShareAPI = UMShareAPI.get(this);
        tvTitle.setText("分享活动详情");
        giftDetailBottomMarketPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        initWebView();
    }

    @Override
    protected void initData() {
        super.initData();
        type = "activity";
        aid = getIntent().getExtras().getString("aid");
        getServer(Url.ACTIVITY_DETAIL, null, "&aid=" + aid, false, null, "get");
    }

    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebChromeClient(new WebChromeClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(webView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
        webView.setOnLoadFinishListener(new ArticleWebView.OnLoadFinishListener() {
            @Override
            public void onLoadFinish() {
                if (webView.getContentHeight()>0){
                    int height = webView.getContentHeight() - scrollView.getMeasuredHeight();
                    if (height > 0) {
                        scrollBottom(height + ll_bottom.getMeasuredHeight() + title.getMeasuredHeight());
                    } else {
                        scrollBottom(0);
                    }
                }
            }
        });
//        //webview监听，webview加载完毕滚到底部
//        webView.setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//            }
//        });
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("activity".equals(type)) {
                result = gson.fromJson(response, GiftResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                setData();
            } else if ("share".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * scrollview滚动到底部
     *
     * @param height
     */
    private void scrollBottom(final int height) {
        ObjectAnimator xTranslate = ObjectAnimator.ofInt(scrollView, "scrollX", 0);
        ObjectAnimator yTranslate = ObjectAnimator.ofInt(scrollView, "scrollY", scrollView.getMeasuredHeight() + height);
        AnimatorSet animators = new AnimatorSet();
        animators.setDuration(1000L);
        animators.playTogether(xTranslate, yTranslate);
        animators.start();
    }

    /**
     * 添加数据
     */
    private void setData() {
        if (result != null) {
            activity = result.getActivity();
            if (null != activity.getName() && !"".equals(activity.getName())) {
                giftDetailTopName.setText(activity.getName());
            } else {
                giftDetailTopName.setText("");
            }
            if (null != activity.getEtime() && !"".equals(activity.getEtime())) {
                giftDetailTopTime.setText("截止日:" + activity.getEtime());
                getGiftDetailBottomTime.setText("截止日:" + activity.getEtime());

            } else {
                giftDetailTopTime.setText("");
                getGiftDetailBottomTime.setText("");
            }
            if (null != activity.getSubject() && !"".equals(activity.getSubject())) {
                giftDetailTopDescribe.setText(activity.getSubject());
            } else {
                giftDetailTopDescribe.setText("");
            }

            refInfo = result.getRefInfo();
            if (null != refInfo.getName() && !"".equals(refInfo.getName())) {
                giftDetailCenterName.setText(refInfo.getName());
                giftDetailBottomName.setText(refInfo.getName());
            } else {
                giftDetailCenterName.setText("");
                giftDetailBottomName.setText("");

            }
            if (null != refInfo.getImages() && !"".equals(refInfo.getImages())) {
                Glide.with(context).load(Url.IMG_URL + refInfo.getImages()).placeholder(R.mipmap.iv_loading).fitCenter().into(giftDetailCenterIamge);
                Glide.with(context).load(Url.IMG_URL + refInfo.getImages()).placeholder(R.mipmap.iv_loading).into(giftDetailBottomImage);
            }

            if (null != refInfo.getMarketprice() && !"".equals(refInfo.getMarketprice())) {
                giftDetailBottomMarketPrice.setText("市场价：" + refInfo.getMarketprice() + "元");
            } else {

            }
            if (null != activity.getDetailsinfo() && !"".equals(activity.getDetailsinfo())) {
                webView.loadDataWithBaseURL(null, getNewContent(activity.getDetailsinfo()), "text/html", "utf-8", null);
            }
            if (null != activity.getAprice() && !"".equals(activity.getAprice())) {
                giftDetailBottomFriendPrice.setText("好友下单价：" + activity.getAprice() + "元");
                giftDetailBottomSaveMoney.setText("立省" + DataUtil.subtract(refInfo.getMarketprice(), activity.getAprice()) + "元");
            } else {
                giftDetailBottomFriendPrice.setText("");
                giftDetailBottomSaveMoney.setText("");
            }
            if (null != activity.getBackinnernum() && !"".equals(activity.getBackinnernum()) && null != activity.getBackredbeanfcustomer() && !"".equals(activity.getBackredbeanfcustomer())) {
                giftDetailBottomFriendMeidou.setText(activity.getBackinnernum() + "美豆 ");
                giftDetailBottomFriendHongdou.setText("+ " + activity.getBackredbeanfcustomer() + "红豆");
            } else if (null != activity.getBackinnernum() && !"".equals(activity.getBackinnernum())) {
                giftDetailBottomFriendMeidou.setText(activity.getBackinnernum() + "美豆 ");
                giftDetailBottomFriendHongdou.setText("");
            } else if (null != activity.getBackredbeanfcustomer() && !"".equals(activity.getBackredbeanfcustomer())) {
                giftDetailBottomFriendMeidou.setText("");
                giftDetailBottomFriendHongdou.setText(activity.getBackredbeanfcustomer() + "红豆");
            } else {
                giftDetailBottomFriendMeidou.setText("");
                giftDetailBottomFriendHongdou.setText("");
            }

            if (null != activity.getBackredbeanfshare() && !"".equals(activity.getBackredbeanfshare())) {
                giftDetailBottomSharerGet.setText(activity.getBackredbeanfshare());
            } else {
                giftDetailBottomSharerGet.setText("");
            }

            storeInfo = result.getStoreInfo();
            if (null != storeInfo.getName() && !"".equals(storeInfo.getName())) {
                giftDetailBottomShopName.setText(storeInfo.getName());
            } else {
                giftDetailBottomShopName.setText("");
            }
            if (null != storeInfo.getAddress() && !"".equals(storeInfo.getAddress())) {
                giftDetailBottomShopAddress.setText(storeInfo.getAddress());
            } else {
                giftDetailBottomShopAddress.setText("");

            }

            if (null != activity.getGattr() && !"".equals(activity.getGattr())) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(activity.getGattr());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Iterator<String> keys = jsonObject.keys();
                String attr = "";
                while (keys.hasNext()) {
                    String next = keys.next();
                    String attrValue = jsonObject.optString(next);
                    attr += attrValue + "/";
                }
                giftDetailBottomCategory.setText(attr.substring(0, attr.length() - 1));

            } else {
                giftDetailBottomCategory.setText("");
            }

            if (null != activity.getAtype() && !"".equals(activity.getAprice())) {
//                if (activity.getAtype().equals("2")){
                if (null != storeInfo.getMphone() && !"".equals(storeInfo.getMphone())) {
                    giftDetailBottomShopPhone.setText(storeInfo.getMphone());
                } else {
                    giftDetailBottomShopPhone.setText("");
                }
//                }else {
//                    if (null!=storeInfo.getPhone()&&!"".equals(storeInfo.getPhone())){
//                        giftDetailBottomShopPhone.setText(storeInfo.getPhone());
//                    }else {
//                        giftDetailBottomShopPhone.setText("");
//                    }
//                }
            }


        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1001 == result.getCode()) {
                Toast.makeText(context, "用户未登录", Toast.LENGTH_LONG);
                finish();
            } else if (6001 == result.getCode()) {
                Toast.makeText(this, "库存不足", Toast.LENGTH_LONG).show();
                finish();
            } else if (6002 == result.getCode()) {
                Toast.makeText(this, "活动未开始", Toast.LENGTH_LONG).show();
                finish();
            } else if (6003 == result.getCode()) {
                Toast.makeText(this, "活动已停止", Toast.LENGTH_LONG).show();
                finish();
            } else if (6004 == result.getCode()) {
                Toast.makeText(this, "店铺 或商家已下架， 活动停止", Toast.LENGTH_LONG).show();
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.ivBack, R.id.tvShare})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvShare:
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
                break;
        }
    }


    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(tvShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                new ShareAction(GiftDetailActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle(result.getActivity().getName()).withMedia(new UMImage(GiftDetailActivity.this, R.mipmap.logo))
                        .withText(result.getActivity().getSubject()).withTargetUrl(Url.BASE_URL + "/activity/giftpacks/index/?sharekey=" + result.getShareKey())
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功了!!!");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("base", "fail");
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Log.i("base", "cancel");
            showShortToast("分享取消了");
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private String getNewContent(String htmltext) {

        String html = "<meta name=\"viewport\" content=\"width=device-width\"><div><p>";


        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");

        }
        Elements elements2 = doc.getElementsByTag("img");
        for (Element element : elements2) {
            element.attr("width", "100%").attr("height", "auto");
        }

        return doc.toString();
    }


}
